import {
    createConcurrentQueue
} from 'some-fun-utils';

// 示例1: 基础用法 - 模拟API请求
async function example1() {
    console.log('=== 示例1: 基础用法 ===');

    // 模拟请求函数
    const fetchUserInfo = async (userId) => {
        const delay = Math.random() * 1000 + 500; // 500-1500ms延迟
        await new Promise(resolve => setTimeout(resolve, delay));

        // 模拟一些请求可能失败
        if (Math.random() < 0.1) {
            throw new Error(`Failed to fetch user ${userId}`);
        }

        return {
            id: userId,
            name: `User${userId}`,
            delay: Math.round(delay)
        };
    };

    const userIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    console.time('Concurrent requests');
    const results = await createConcurrentQueue(userIds, fetchUserInfo, {
        maxConcurrent: 3, // 最大并发3个请求
        stopOnError: false // 遇到错误不停止
    });
    console.timeEnd('Concurrent requests');

    console.log('Results:', results);

    // 统计成功和失败数量
    const fulfilled = results.filter(r => r.status === 'fulfilled').length;
    const rejected = results.filter(r => r.status === 'rejected').length;
    console.log(`成功: ${fulfilled}, 失败: ${rejected}`);
}

// 示例2: 遇到错误停止
async function example2() {
    console.log('\n=== 示例2: 遇到错误停止 ===');

    const riskyRequest = async (id) => {
        await new Promise(resolve => setTimeout(resolve, 200));
        if (id === 3) {
            throw new Error('Critical error at id 3');
        }
        return `Result ${id}`;
    };

    const ids = [1, 2, 3, 4, 5];

    const results = await createConcurrentQueue(ids, riskyRequest, {
        maxConcurrent: 2,
        stopOnError: true // 遇到错误立即停止
    });

    console.log('Results with stop on error:', results);
}

// 示例3: 文件下载场景
async function example3() {
    console.log('\n=== 示例3: 文件下载场景 ===');

    const downloadFile = async (fileInfo) => {
        const {
            url,
            filename
        } = fileInfo;
        console.log(`开始下载: ${filename}`);

        // 模拟下载过程
        const downloadTime = Math.random() * 2000 + 1000;
        await new Promise(resolve => setTimeout(resolve, downloadTime));

        console.log(`下载完成: ${filename} (${Math.round(downloadTime)}ms)`);
        return {
            filename,
            size: Math.round(Math.random() * 1024 * 1024)
        };
    };

    const files = [{
            url: 'http://example.com/file1.zip',
            filename: 'file1.zip'
        },
        {
            url: 'http://example.com/file2.zip',
            filename: 'file2.zip'
        },
        {
            url: 'http://example.com/file3.zip',
            filename: 'file3.zip'
        },
        {
            url: 'http://example.com/file4.zip',
            filename: 'file4.zip'
        },
        {
            url: 'http://example.com/file5.zip',
            filename: 'file5.zip'
        }
    ];

    console.time('Download all files');
    const results = await createConcurrentQueue(files, downloadFile, {
        maxConcurrent: 2 // 同时下载2个文件
    });
    console.timeEnd('Download all files');

    console.log('Download results:', results);
}

// 运行所有示例
async function runExamples() {
    try {
        await example1();
        await example2();
        await example3();
    } catch (error) {
        console.error('Error running examples:', error);
    }
}

runExamples();